package com.ljw.vendingmachine;


import android.content.Intent;
import android.os.Handler;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.firefly.api.serialport.SerialPort;
import com.ljw.vendingmachine.base.BaseActivity;
import com.ljw.vendingmachine.bean.Goods;
import com.ljw.vendingmachine.bean.GoodsType;
import com.ljw.vendingmachine.bean.MessageEvent;
import com.ljw.vendingmachine.service.WebSocketService;
import com.ljw.vendingmachine.utils.Constant;
import com.ljw.vendingmachine.utils.GsonUtil;
import com.ljw.vendingmachine.utils.LayoutUtil;
import com.ljw.vendingmachine.utils.LogUtil;
import com.ljw.vendingmachine.utils.LongClickUtils;
import com.ljw.vendingmachine.widget.BaseVideoPlay;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.chad.library.adapter.base.BaseQuickAdapter.SCALEIN;

public class MainActivity extends BaseActivity {
    @BindView(R.id.rv_goods)
    RecyclerView rv_goods;
    @BindView(R.id.video_play)
    BaseVideoPlay video_play;
    @BindView(R.id.layout_video_parent)
    LinearLayout layout_video_parent;
    @BindView(R.id.more_goods)
    TextView more_goods;
    private BaseQuickAdapter<Goods, BaseViewHolder> goods_list_adapter;
    private PopupWindow goodscar;
    private View inflate;
    //更多页面分类
    List<GoodsType> types = new ArrayList<>();
    public static List<Goods> goodsMap = new ArrayList<>();


    @Override
    public int setContentView() {
        return R.layout.activity_main;
    }

    @Override
    public void initView() {

        video_play.getBackButton().setVisibility(View.GONE);
        video_play.setIsTouchWigetFull(false);
        video_play.setIsTouchWiget(false);
        video_play.getStartButton().setVisibility(View.GONE);
        video_play.initSetting();
        video_play.setLooping(true);
        //加载购物车布局
        inflate = LayoutInflater.from(this).inflate(R.layout.goods_car_layout, null, false);
        goodscar = LayoutUtil.createPopupWindow(inflate);
        rv_goods.setLayoutManager(new GridLayoutManager(this, 4));
        goods_list_adapter = new BaseQuickAdapter<Goods, BaseViewHolder>(R.layout.goods_item, null) {
            @Override
            protected void convert(BaseViewHolder helper, Goods item) {
                helper.setText(R.id.goods_name, item.getGoodsName());
                helper.setText(R.id.goods_price, Html.fromHtml(String.format(getString(R.string.goods_price), item.getGoodsPrice())));
                helper.setText(R.id.tv_stockNum, "库存:" + item.getStockNum());
                Glide.with(MainActivity.this)
                        .load(item.getPicUrl())
                        .into((ImageView) helper.getView(R.id.goods_img));
                helper.addOnClickListener(R.id.btn_addtocar);
            }
        };
        //设置加载动画
        goods_list_adapter.openLoadAnimation(SCALEIN);
        rv_goods.setAdapter(goods_list_adapter);
        //设置item加入购物车点击事件
        goods_list_adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                Goods item = goods_list_adapter.getItem(position);
                addTOCar(item);
            }
        });

    }





    public void setPopOnClick(View pop) {
        View disMiss = pop.findViewById(R.id.tv_PopDiss);
        disMiss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goodscar.dismiss();
            }
        });
        View tv_topay = pop.findViewById(R.id.tv_topay);
        tv_topay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goodscar.dismiss();
            }
        });

    }

    /**
     * @param goods 添加到购物车
     */
    public void addTOCar(Goods goods) {

        List<Goods> data = goodsMap;
        if (0 == goods.getStockNum()) {
            Toast.makeText(this, "货架此商品数量为0,无购买！", Toast.LENGTH_SHORT).show();
            return;
        }
        if (data.contains(goods)) {

            int index = data.indexOf(goods);
            Goods goods1 = data.get(index);
            int stockNum = goods1.getStockNum();
            int stockNumadd1 = stockNum + 1;
            if (stockNum < stockNumadd1) {
                goods1.setStockNum(stockNum);
                Toast.makeText(this, "此商品货架数量" + stockNum, Toast.LENGTH_SHORT).show();
                return;
            } else {
                goods1.setStockNum(stockNumadd1);


            }

            //    car_listAdapter.notifyItemChanged(index);
        } else {
            Goods bean = (Goods) goods.clone();
            bean.setStockNum(1);
            data.add(bean);
        }
        toMoreGoods();
        //   initAnimation(view);

    }

    @Override
    public void initData() {
        EventBus.getDefault().register(this);
        StartWebSocketService();
        LongClickUtils.setLongClick(new Handler(), more_goods, 10000, new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                startActivity(new Intent(MainActivity.this, SelectSetting.class));
                   finish();
                return false;
            }
        });
    }


    /**
     * 跳转到更多页面
     */
    @OnClick(R.id.more_goods)
    public void toMoreGoods() {
        Intent intent = new Intent(this, MoreGoodsActivity.class);
        intent.putExtra("types", (Serializable) types);
        startActivity(intent);
    }

    public void initgoodscar(View view) {
//       view.findViewById(R.id.)

    }

    @Override
    public void afterSetContentView() {
        super.afterSetContentView();

    }

    /**
     * 每次对倒
     */
    @Override
    protected void onResume() {
        super.onResume();
        video_play.onVideoResume();
        goodsMap.clear();
        MessageEvent mes = new MessageEvent();
        mes.setCode(Constant.SEND_CMD);
        mes.setData(Constant.COMD_GET_MAIN_GOODS);
        EventBus.getDefault().postSticky(mes);


    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        GSYVideoManager.releaseAllVideos();
        EventBus.getDefault().unregister(this);

    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onReceiveData(MessageEvent event) {
        if (Constant.EVENTBUS_CODE_MAIN_GOODS_LIST == event.getCode()) {
            if (goods_list_adapter != null) {
                JSONObject data = (JSONObject) event.getData();
                //商品列表
                try {
                    String videoURL = data.getString("video");
//                    video_play.setUp("http://9890.vod.myqcloud.com/9890_4e292f9a3dd011e6b4078980237cc3d3.f20.mp4", true, "");
                    if (videoURL != null && !videoURL.equals(video_play.getmOriginUrl())) {
                        video_play.setUp(videoURL, true, "");
                        video_play.startPlayLogic();
                        video_play.initSetting();
                    }


                    List<Goods> list = GsonUtil.GsonToList(data.getJSONArray("list").toString(), Goods[].class);
                    goods_list_adapter.replaceData(list);
                    //商品分类
                    JSONArray type = data.getJSONArray("type");
                    List<GoodsType> type_s = GsonUtil.GsonToList(type.toString(), GoodsType[].class);
                    types.clear();
                    types.addAll(type_s);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        if (Constant.RE_CONNECT == event.getCode()) {
            if ((boolean) event.getData()) {
                dialog.show();
            } else {
                dialog.dismiss();
            }
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        video_play.onVideoPause();
    }





    /*开启websocket 服务
     */
    public void StartWebSocketService() {
        Intent intent = new Intent(this, WebSocketService.class);
        startService(intent);
    }


}
